const mongoose = require('mongoose')
const glob = require('glob')
const {resolve} = require('path')

const db = "mongodb://localhost/simle-db"

mongoose.Promise = global.Promise

exports.initSchemas = () =>{
    glob.sync(resolve(__dirname,'./schema/','**/*.js')).forEach(require)
}

exports.connect = () => {
    mongoose.connect(db);//连接数据库
    let maxNum  = 0;
    return new Promise((resolve,reject) => {
        
        //当断开时重新连接
        mongoose.connection.on('disconnected',()=>{
            if(maxNum < 3){
                maxNum++;
              //重新连接
              mongoose.connect(db);
            }else{
                reject()
                throw new Error('连接超时，数据出错!');
            }
            
        });
        //当连接出错时
        mongoose.connection.on('error',err => {
            if(maxNum < 3){
                maxNum++;
              //重新连接
              mongoose.connect(db);
            }else{
                reject()
                throw new Error('连接超时，数据出错!');
            }
        });
        //连接打开时
        mongoose.connection.on('open',() => {
            console.log('Mongoose Connected successfully!')
            resolve() 
        });
    });
   
}